package com.example.controller;

import com.example.util.AliOSSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private AliOSSUtils aliOSSUtils;

    @PostMapping("/create")
    public String create(MultipartFile file) throws IOException {
        String upload = aliOSSUtils.upload(file);
        return upload;
    }



    @PostMapping("/xxx")
    public String uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("chunk") int chunk, // 分片序号
            @RequestParam("totalChunks") int totalChunks, // 总分片数量
            @RequestParam("identifier") String identifier // 文件唯一标识，用于区分不同文件
    ) throws IOException {
        // 确定分片存储的临时文件夹
        File tempDir = new File("D:\\temp" + identifier);
        if (!tempDir.exists()) {
            tempDir.mkdirs();
        }

        // 分片文件存储路径
        File tempFile = new File(tempDir, identifier + "." + chunk);
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            fos.write(file.getBytes());
        }

        // 检查是否所有分片都已上传
        boolean allChunksUploaded = true;
        for (int i = 0; i < totalChunks; i++) {
            File chunkFile = new File(tempDir, identifier + "." + i);
            if (!chunkFile.exists()) {
                allChunksUploaded = false;
                break;
            }
        }

        // 如果所有分片都上传完毕，合并分片
        if (allChunksUploaded) {
            File mergedFile = new File(tempDir.getParentFile(), identifier);
            mergeFiles(tempDir, mergedFile);
            // 可以选择删除分片或者重命名
            tempDir.delete();
        }

        return "Chunk uploaded";
    }

    private void mergeFiles(File tempDir, File mergedFile) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(mergedFile)) {
            File[] files = tempDir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.getName().startsWith(mergedFile.getName())) {
                        try (FileInputStream fis = new FileInputStream(file)) {
                            byte[] buffer = new byte[1024];
                            int length;
                            while ((length = fis.read(buffer)) > 0) {
                                fos.write(buffer, 0, length);
                            }
                        }
                    }
                }
            }
        }
    }


}
